<?php
class Listing_Form_PostAnAddMaidForm extends Listing_Form_PostAnAddForm
{
    private $_preview_link = '';

    private $_category;
    private $_adid;
    private $_listing;
    private $_viewscript;

    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $formDecorators = array(
            'PrepareElements',
            array('ViewScript', array('viewScript' => 'index/customization/maid-post-an-ad.phtml'))
    );

    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('placement' => 'prepend')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
        array('HtmlTag', array('tag' => 'p', 'class' => 'price radio text')),
        array('Description', array('placement' => 'prepend', 'tag' => 'label')),
    );

    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'APPEND')),
    );
    
    protected $elementMultiCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementSelectDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array()),
    );
    
    protected $elementSelectDecorators1 = array(
        'ViewHelper',
        'Errors',
        array('Label', array()),
        array(array('row' => 'HtmlTag'), array('class'=>'select1')),
    );

    public function __construct($options = array())
    {
        $this->_preview_link = !empty($options['preview_link']) ? $options['preview_link'] : '';
        $this->_category = !empty($options['category']) ? $options['category'] : array();
        $this->_adid = !empty($options['adid']) ? $options['adid'] : array();
        $this->_listing = !empty($options['listing']) ? $options['listing'] : new StdClass();
        $this->_viewscript = !empty($options['viewscript']) ? $options['viewscript'] : 'index/customization/maid-post-an-ad.phtml';
        parent::__construct();
    }
    
    public function init()
    {
        parent::init();
        $element = new Zend_Form_Element_Hidden('adid');
        $element->setValue((string) $this->_adid);
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        $this->addElement($element);

        $i = 0;
        foreach($this->_category  as $cat) {
            $i++;
            $element = new Zend_Form_Element_Hidden('category_link'.$i);
            $element->setValue((string) $cat->_id);
            $element->setDecorators(array(
                    'ViewHelper'
                )
            );
            $this->addElement($element);
        }
        $cat_str = '<ul>';
        foreach ($this->_category as $cat_id) {
            $cat_str .= '<li>';
            $tmp = array();
            $category = Model_Category::find($cat_id->_id);
            foreach ($category->getParentTree() as $cat) {
                $tmp[] = $cat->name;
            }
            $cat_str .= implode(' > ', $tmp);
            $cat_str .= '</li>';
        }
        $cat_str .= '</ul>';
        $this->setDescription($cat_str);

        //Title
        $this->addElement('text', 'tl_en', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));
        
        /*
        //Age
        $this->addElement('text', 'age', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('int', true, array('messages' => 'Only numbers are allowed')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'required'     => true,
        ));
       */
        
        // Date of birth
        $this->addElement('datePicker', 'dateofbirth', array(
            'jQueryParams' => array(
               'defaultDate' => '01/01/'.(date('Y')-18),
               'dateFormat'  => 'dd/mm/yy',
               'changeMonth' => true,
               'changeYear' => true,
               'yearRange' => (date('Y')-70).':'.(date('Y')-18) 
            ),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'required' => true
        ));
//        var_dump($this->getElement('availabletostart')->getDecorators());exit;
        $this->getElement('dateofbirth')->removeDecorator('label')->removeDecorator('HtmlTag');        
        
        // Education
        $this->addElement('select', 'education', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Maid::getEducationPostAd(),
            'required'     => true,
        ));

        // Languages
        /*
        $this->addElement('multiCheckbox', 'languages', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Maid::getLanguagesPostAd(),
            'required'     => true,
        ));
         *
         */

        $this->addElement('autoComplete', 'languages_auto', array(
            'jQueryParams' => array(
                'source' => '/search/get-attribute?c=dh&f=language',
                'delay' => 0,
//                'source' => 'languages_available',
            ),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            
            'decorators' => array(
                    'UiWidgetElement',
                    'Errors',
                    array('Label', array('escape' => false)),
                    //array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'select')),
            ),
            'required'     => false,
        ));        
        
        // Nationality
        $this->addElement('select', 'nationality', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Maid::getNationalityPostAd(),
            'required'     => true,
        ));

        // Religion
        $this->addElement('select', 'religion', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Maid::getReligionPostAd(),
            'required'     => true,
        ));

        // Marital Status
        $this->addElement('select', 'maritalstatus', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Maid::getMaritalStatusPostAd(),
            'required'     => true,
        ));

        //Gender
        $this->addElement('radio', 'gender', array(
            'filters'    => array('StringTrim'),
            'separator' => ' ',
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                //array('Label', array()),
                array(array('row' => 'HtmlTag'), array('class'=>'radio')),
            ),
            'multiOptions' => array(
                2 => 'Female',
                1 => 'Male'
            ),
            'required'     => true,
        ));
        $this->getElement('gender')->removeDecorator('label');
    
        // Available to Start
        $this->addElement('datePicker', 'availabletostart', array(
            'jQueryParams' => array(
               'defaultDate' => date('d/m/Y', time()),
               'dateFormat'  => 'dd/mm/yy',
            ),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'required' => true
        ));
//        var_dump($this->getElement('availabletostart')->getDecorators());exit;
        $this->getElement('availabletostart')->removeDecorator('label')->removeDecorator('HtmlTag');

        //Employment Type
        $this->addElement('multiCheckbox', 'employmenttype', array(
            'filters'    => array('StringTrim'),
            'separator' => ' ',
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                //array('Label', array()),
                array(array('row' => 'HtmlTag'), array('class'=>'radio')),
            ),
            'multiOptions' => Model_Listing_Maid::getEmploymentTypePostAd(),
            'required'     => true,
        ));
        $this->getElement('employmenttype')->removeDecorator('label');
        
        // Visa Status
        $this->addElement('select', 'visastatus', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            //'multiOptions' => array_slice(Model_Listing_Maid::getVisastatusPostAd(), 0, 5),
            'multiOptions' => Model_Listing_Maid::getVisastatusPostAd(),
            'required'     => false,
        ));
        
        // Salary
        $this->addElement('text', 'salary', array(
            'validators' => array(
                array('Float', true, array('messages' => 'Only numbers are allowed')),
            ),
            'decorators' => array('ViewHelper'),
            'required'   => false,
        ));       
        
       
        // Contact number
        $this->addElement('text', 'contact_number', array(
            'decorators' => array('ViewHelper'),
            'required'   => true,
        ));               

        // Weight
        $this->addElement('text', 'weight', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('Int', true, array('messages' => 'Only numbers are allowed')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));        

        // Height
        $this->addElement('text', 'height', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('Int', true, array('messages' => 'Only numbers are allowed')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        // Chinese Zodiac
        $this->addElement('select', 'chinesezodiac', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Maid::getChineseZodiacPostAd(),
            'required'     => false,
        ));

        // Horoscope
        $this->addElement('select', 'horoscope', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Maid::getHoroscopePostAd(),
            'required'     => false,
        ));

        // Description
        $this->addElement('textarea', 'cs_en', array(
            'filters'    => array('StringTrim'),
            'decorators' => $this->elementDecorators,
            'rows'=>'',
            'required'   => false,
        ));
   
        // Reason for leaving previous job
        $this->addElement('textarea', 'rlj_en', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'rows'=>'',
            'required'   => true,
        ));

   
        // Previous employers references
        $this->addElement('textarea', 'pe_en', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'rows'=>'',
            'required'   => false,
        ));        
        
        // Skill Level Western
        $this->addElement('select', 'skilllevelwestern', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Maid::getSkillLevelPostAd(),
            'required'     => true,
        ));

        // Skill Level Chinese
        $this->addElement('select', 'skilllevelchinese', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Maid::getSkillLevelPostAd(),
            'required'     => true,
        ));
        


        // Specialities
        $this->addElement('text', 'spo_en', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        // Year Experience Children
        $this->addElement('select', 'yearexpchildren', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'required'     => true,
        ));
               
        // Year Experience Newborn
        $this->addElement('select', 'yearexpnewborn', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'required'     => true,
        ));

        // Year Experience Disable
        $this->addElement('select', 'yearexpdisable', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'required'     => true,
        ));

        // Year Experience Elderly
        $this->addElement('select', 'yearexpelderly', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'required'     => true,
        ));
       
        // Householding and Cleaning
        $this->addElement('multiCheckbox', 'householdcleaning', array(
            'filters'    => array('StringTrim'),
            'separator' => ' ',
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => array(
                'ViewHelper',
                'Errors',
                //array('Label', array()),
                //array(array('row' => 'HtmlTag'), array('class'=>'checkbox')),
            ),
            'multiOptions' => Model_Listing_Maid::getHouseholdCleaningPostAd(),
            'required'     => false,
        ));
        $this->getElement('householdcleaning')->removeDecorator('label');
        



        // Year Experience Hong Kong
        $this->addElement('select', 'yearexphk', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));

        // Year Experience Indonesia
        $this->addElement('select', 'yearexpind', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));

        // Year Experience Malaysia
        $this->addElement('select', 'yearexpmal', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));

        // Year Experience Middle East
        $this->addElement('select', 'yearexpmid', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));
        
        // Year Experience Philippines
        $this->addElement('select', 'yearexpphil', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));

        // Year Experience Singapore
        $this->addElement('select', 'yearexpsing', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));

        // Year Experience Taiwan
        $this->addElement('select', 'yearexptai', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));

        // Year Experience Thailand
        $this->addElement('select', 'yearexpthai', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));

        // Year Experience china
        $this->addElement('select', 'yearexpchina', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));

        // Year Experience Other
        $this->addElement('select', 'yearexpoth', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Listing_Maid::getYearExperiencePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators,
            'required'   => false,
        ));

        // Add more
        $this->addElement('hidden', 'add_more_checkbox', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array(array('data' => 'HtmlTag'), array('style' => 'display:none')),
            ),
            'value'   => 1,
            'required'   => false,
        ));
        
        $this->addElement('button', 'validate', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'submit',
            'label'       => 'Post your ad',
            'decorators'  => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'button_em')))),
        ));

        $this->addElement('button', 'preview', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'button',
            'label'       => 'Preview',
            //'description' => '<a href="'.$this->_preview_link.'">Preview</a>',
            'decorators'  => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'preview button')))),
        ));


        $opt = $this->getDecorator('ViewScript')->getOptions();
        $opt['category']     = $this->_category;
        $opt['adid']         = $this->_adid;
        $opt['listing']      = $this->_listing;
        $opt['preview_link'] = $this->_preview_link;
        $opt['viewScript']   = $this->_viewscript;

        $this->getDecorator('ViewScript')->setOptions($opt);

    }

    public function save($preview = false)
    {
        if (empty($this->_adid)) {
            $ad = new Model_Listing_Regular();
        } else {
            $ad = Model_Listing_Preview::find(new MongoId($this->_adid));
        }

        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
            if ($user->role == Model_User::ROLE_ADMIN) {
                if(empty($ad->us)) {
                    $ad->user        = $user->_id;    
                }
            } else {
                $ad->user        = $user->_id;
            }
            if (empty($this->status)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
            }
        } else {
            $ad->status = 6;
        }

        //print_r($ad);exit;

        //Requiered Attributs
        // $ad->tl_en                      = $_POST['tl_en'];
        //$ad->dateofbirth                = $_POST['dateofbirth'];
		
		$classname = Model_Listing::getInstanceClassname((array)$this->_listing->ca);
		$translateFields = $classname::getTranslationFormField();
		if (Zend_Registry::get('current_language') == 'en'){
			if (empty($ad->ad_type)) 
			$ad->ad_type = Model_Listing::ORIGINAL_LANGUAGE_EN;
			$ft = 'en';
			$tt = 'zh-TW';
			
			foreach($translateFields as $v => $r){
				$ad->{$v} = $this->getValue($v);
				
				if (empty($ad->{str_replace('en','tc', $v)})){
					$ad->{str_replace('en','tc', $v)} = Ac_Translation::execute($this->getValue($v), $tt, $ft);
				}
				
			}

		} else {
			if (empty($ad->ad_type)) 
			$ad->ad_type = Model_Listing::ORIGINAL_LANGUAGE_TC;
			$ft = 'zh-TW';
			$tt = 'en';		
			
			foreach($translateFields as $v => $r){
				$ad->{str_replace('en','tc', $v)} = $this->getValue($v);
				
				
				if (empty($ad->{$v})){
					$ad->{$v} = Ac_Translation::execute($this->getValue($v), $tt, $ft);
				}
		
			}
		}
		
        list($day,$month,$year) = explode('/',$_POST['dateofbirth']);
        $ad->dateofbirth                = new MongoDate(mktime(0,0,0,$month, $day, $year));
                
        $ad->education                  = $_POST['education'];
        $ad->languages                  = (array)$_POST['languages'];
        $ad->nationality                = $_POST['nationality'];
        $ad->religion                   = $_POST['religion'];
        $ad->maritalstatus              = $_POST['maritalstatus'];
        $ad->gender                     = $_POST['gender'];
        $ad->availabletostart           = $_POST['availabletostart'];
        $ad->employmenttype             = $_POST['employmenttype'];
        $ad->visastatus                 = $_POST['visastatus'];
        // $ad->rlj_en   					= $_POST['rlj_en'];
        // $ad->pe_en         				= $_POST['pe_en'];
        $ad->contact_number             = $_POST['contact_number'];

        if (isset($_POST['skilllevelwestern']) && is_numeric($_POST['skilllevelwestern'])) {
            $ad->skilllevelwestern          = $_POST['skilllevelwestern'];
        }
        if (isset($_POST['skilllevelchinese']) && is_numeric($_POST['skilllevelchinese'])) {
            $ad->skilllevelchinese          = $_POST['skilllevelchinese'];
        }
      
        /* if (!empty($_POST['specialities'])) {
            $ad->specialities          = $_POST['specialities'];
        } */

        if (!empty($_POST['yearexpnewborn']) || $_POST['yearexpnewborn'] == 0) {$ad->yearsexperiencenewborn     = $_POST['yearexpnewborn'];}
        if (!empty($_POST['yearexpchildren']) || $_POST['yearexpchildren'] == 0) {$ad->yearsexperiencechildren    = $_POST['yearexpchildren'];}
        if (!empty($_POST['yearexpdisable']) || $_POST['yearexpdisable'] == 0) {$ad->yearsexperiencedisable     = $_POST['yearexpdisable'];}
        if (!empty($_POST['yearexpelderly']) || $_POST['yearexpelderly'] == 0) {$ad->yearsexperienceelderly     = $_POST['yearexpelderly'];}

        if (!empty($_POST['householdcleaning'])) {
            $ad->householdcleaning          = (array) $_POST['householdcleaning'];
        }

        
        //var_dump($_POST['country'],  $_POST['yoe']);
        $yoec = array();
        foreach($_POST['country'] as $k => $country) {
            if ($_POST['yoe'][$k] == '') {
                continue;
            }
            
            $yoec[$country] = $_POST['yoe'][$k];
            
            /*
            switch($country) {
                case Model_Listing_Maid::COUNTRY_HONGKONG:
                        $yoe[Model_Listing_Maid::COUNTRY_HONGKONG] = $_POST['yoe'][$k];
                    break;
                case Model_Listing_Maid::COUNTRY_INDONESIA:
                    $ad->indonesiayearsexperience    = $_POST['yoe'][$k];
                    break;
                case Model_Listing_Maid::COUNTRY_MALAYSIA:
                    $ad->malaysiayearsexperience    = $_POST['yoe'][$k];
                    break;
                case Model_Listing_Maid::COUNTRY_MIDDLEEAST:
                    $ad->middleeastyearsexperience    = $_POST['yoe'][$k];
                    break;
                case Model_Listing_Maid::COUNTRY_PHILIPPINES:
                    $ad->philippinesyearsexperience    = $_POST['yoe'][$k];
                    break;
                case Model_Listing_Maid::COUNTRY_SINGAPORE:
                    $ad->singaporeyearsexperience    = $_POST['yoe'][$k];
                    break;
                case Model_Listing_Maid::COUNTRY_TAIWAN:
                    $ad->taiwanyearsexperience    = $_POST['yoe'][$k];
                    break;
                case Model_Listing_Maid::COUNTRY_THAILAND:
                    $ad->thailandyearsexperience    = $_POST['yoe'][$k];
                    break;
                case Model_Listing_Maid::COUNTRY_CHINA:
                    $ad->chinayearsexperience    = $_POST['yoe'][$k];
                    break;
            }
             * 
             */
        }
        $ad->yoe_country = $yoec;
        //var_dump($ad);exit;
        /*
        if (!empty($_POST['yearexphk'])) {$ad->hongkongyearsexperience    = $_POST['yearexphk'];}
        if (!empty($_POST['yearexpind'])) {$ad->indonesiayearsexperience   = $_POST['yearexpind'];}
        if (!empty($_POST['yearexpmal'])) {$ad->malaysiayearsexperience    = $_POST['yearexpmal'];}
        if (!empty($_POST['yearexpmid'])) {$ad->middleeastyearsexperience  = $_POST['yearexpmid'];}
        if (!empty($_POST['yearexpphil'])) {$ad->philippinesyearsexperience = $_POST['yearexpphil'];}
        if (!empty($_POST['yearexpsing'])) {$ad->singaporeyearsexperience   = $_POST['yearexpsing'];}
        if (!empty($_POST['yearexptai'])) {$ad->taiwanyearsexperience      = $_POST['yearexptai'];}
        if (!empty($_POST['yearexpthai'])) {$ad->thailandyearsexperience    = $_POST['yearexpthai'];}
        if (!empty($_POST['yearexpchina'])) {$ad->chinayearsexperience       = $_POST['yearexpchina'];}
        */
        
        
        
        //Optional Attributs
        if (!empty($_POST['weight'])) {$ad->weight                      = $_POST['weight'];}
        if (!empty($_POST['height'])) {$ad->height                      = $_POST['height'];}
        //if (!empty($_POST['description'])) {$ad->description            = $_POST['description'];}

        $ad->salary         = (int)$_POST['salary'];

        //force the area to online only since it's not location based
        $ad->area = new MongoId(ONLINE_ONLY_AREA);

        
        foreach ((array) $_REQUEST['category'] as $cat) {
            $tmp = new MongoId($cat);
            $ad->addCategory($tmp);
        }

        $this->continueFillup();
        if (!$preview) {
            $ad = Model_Listing_Preview::saveAsListing($ad);
            Model_Listing_Preview::remove(array('_id' => $ad->_id));
        } else {
            //$ad = Model_Listing_Preview::convertFromListing($ad);
            $ad->save();
        }
        return $ad;
    }

    protected function continueFillup()
    {

    }

    public function isValid($post = array())
    {
        $test1 = parent::isValid($post);
        $test2 = true;

        //Check Bad Words in Title
        if (Ac_Util::checkBadWord($_POST['tl_en'])) {
            $this->getElement('tl_en')->addError('Your Ad contains banned words');
            $test2 = false;
        }

        //Check Bad Words in Description
        if (Ac_Util::checkBadWord($_POST['tl_en'])) {
            $this->getElement('cs_en')->addError('Your Ad contains banned words');
            $test2 = false;
        }

        //Check if language is empty since it's not a regular field
        if (empty($_POST['languages'])) {
            $this->getElement('languages_auto')->addError('This information is required');
            $test2 = false;
        }
        
        //Regex Title contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['tl_en'])) {
            $test2 = false;
        }
        //Regex description contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['rlj_en'])) {
            $test2 = false;
        }
        //Regex previous_employers contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['pe_en'])) {
            $test2 = false;
        }
        //Regex description maid contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['cs_en'])) {
            $test2 = false;
        }

        if (!empty($_POST['availabletostart'])) {
            $validate  = new Zend_Validate_Date(array('format' => 'd/m/Y'));
            $validate->setDisableTranslator(true);
            $error = array();
            if (!preg_match('#(\d){2}/(\d){2}/(\d){4}#', $_POST['availabletostart'], $match)) {
                $tpl = $validate->getMessageTemplates();
                $this->getElement('availabletostart')->addError(str_replace('%format%', 'dd/mm/yyyy', $tpl[Zend_Validate_Date::FALSEFORMAT]));
            }
            
            if (!$validate->isValid($_POST['availabletostart'])) {
                
                if ($arr = current($validate->getMessages())) {
                    $this->getElement('availabletostart')->addError($arr);
                    //array('Date', true, array('messages' => array(Zend_Validate_Date::FALSEFORMAT => 'It must be a date'))),
                }
            }
        }
        
        //Check the two validations
        if ($test1 & $test2){
            return true;
        }
        else {
            return false;
        }
    }
    
    public function __toString()
    {
        $view = Zend_Registry::get('Zend_View');
        $str = '

                $j("a.remove").click(function() {
                    $j(".lng_"+$(this).attr("id")).remove();
                    if($j(".tag lng_id").first().text().indexOf(" ")) {
                        //$j(".tag lng_id").first().text()
                    }
                });

                var to_add_language = "";
                $j("#languages_auto").bind( "autocompleteselect", function(event, ui) {
                    //$j("input").attr({name:"languages[]"}, {value:ui.item.value}).insertAfter($j("#languages_auto"));
                    $j("#lng_cnt").after($j("<input/>").attr({name:"languages[]", value:ui.item.value, type:"hidden", "class":"lng_"+ui.item.value}));
                    var remove = $j("<a/>").attr({id:ui.item.value, "class":"remove lng_"+ui.item.value}).html(" ('.$view->t('Remove').')").click(function() {
                        $j(".lng_"+ui.item.value).remove();
                    });
                    $j("#lng_cnt").append($j("<span/>").attr({"class":"tag lng_"+ui.item.value}).html(to_add_language + ui.item.label).append(remove));
                    $j("#languages_auto").attr("value","");
                    to_add_language = ", ";
                    return false;
                });
        ';
        $this->view->JQuery()->addJavascript($str);
        return parent::__toString();
    }    


    public function populate(array $arr)
    {
        parent::populate($arr);
        
        //var_dump($arr, $this->getElement('title')->getValue());exit;
        /* if (empty($arr['tl_en'])) {
            $this->getElement('tl_en')->setValue($this->_listing->tl_en);
        } */

		if (Zend_Registry::get('current_language') == 'en'){
			$ft = 'en';
			$tt = 'zh-TW';
			
            $this->getElement('tl_en')->setValue($this->_listing->tl_en);
			$this->getElement('rlj_en')->setValue($this->_listing->rlj_en);
			$this->getElement('pe_en')->setValue($this->_listing->pe_en);
			$this->getElement('spo_en')->setValue($this->_listing->spo_en);
			$this->getElement('cs_en')->setValue($this->_listing->cs_en);
			
			
		} else {
			$ft = 'zh-TW';
			$tt = 'en';
			
			$this->getElement('tl_en')->setValue($this->_listing->tl_tc);
			$this->getElement('rlj_en')->setValue($this->_listing->rlj_tc);
			$this->getElement('pe_en')->setValue($this->_listing->pe_tc);
			$this->getElement('spo_en')->setValue($this->_listing->spo_tc);
			$this->getElement('cs_en')->setValue($this->_listing->cs_tc);
		}
		
        if (empty($arr['education'])) {
            $this->getElement('education')->setValue($this->_listing->education);
        }
        if (empty($arr['nationality'])) {
            $this->getElement('nationality')->setValue($this->_listing->nationality);
        }
        if (empty($arr['religion'])) {
            $this->getElement('religion')->setValue($this->_listing->religion);
        }
        if (empty($arr['maritalstatus'])) {
            $this->getElement('maritalstatus')->setValue($this->_listing->maritalstatus);
        }
        if (empty($arr['salary'])) {
            $this->getElement('salary')->setValue($this->_listing->salary);
        }
        if (empty($arr['gender'])) {
            $this->getElement('gender')->setValue($this->_listing->gender);
        }
        if (empty($arr['availabletostart'])) {
            $this->getElement('availabletostart')->setValue($this->_listing->availabletostart);
        }
        if (empty($arr['employmenttype'])) {
            $this->getElement('employmenttype')->setValue($this->_listing->employmenttype);
        }
        if (empty($arr['visastatus'])) {
            $this->getElement('visastatus')->setValue($this->_listing->visastatus);
        }
        if (empty($arr['contact_number'])) {
            $this->getElement('contact_number')->setValue($this->_listing->contact_number);
        }
/*         if (empty($arr['reasonleavingpreviousjob'])) {
            $this->getElement('reasonleavingpreviousjob')->setValue($this->_listing->reasonleavingpreviousjob);
        }
   
        if (empty($arr['previous_employers'])) {
            $this->getElement('previous_employers')->setValue($this->_listing->previous_employers);
        }
 */        
        if (empty($arr['skilllevelwestern'])) {
            $this->getElement('skilllevelwestern')->setValue($this->_listing->skilllevelwestern);
        }
       
        if (empty($arr['skilllevelchinese'])) {
            $this->getElement('skilllevelchinese')->setValue($this->_listing->skilllevelchinese);
        }
       
        /* if (empty($arr['specialities'])) {
            $this->getElement('specialities')->setValue($this->_listing->specialities);
        } */

        if (empty($arr['yearexpnewborn'])) {
            $this->getElement('yearexpnewborn')->setValue(!is_numeric($this->_listing->yearsexperiencenewborn) ? '': $this->_listing->yearsexperiencenewborn);
        }
        if (empty($arr['yearexpchildren'])) {
            $this->getElement('yearexpchildren')->setValue(!is_numeric($this->_listing->yearsexperiencechildren) ? '': $this->_listing->yearsexperiencechildren);
        }
        if (empty($arr['yearsexperiencedisable'])) {
            $this->getElement('yearexpdisable')->setValue(!is_numeric($this->_listing->yearsexperiencedisable) ? '': $this->_listing->yearsexperiencedisable);
        }
        if (empty($arr['yearsexperienceelderly'])) {
            $this->getElement('yearexpelderly')->setValue(!is_numeric($this->_listing->yearsexperienceelderly) ? '': $this->_listing->yearsexperienceelderly);            
        }

        if (empty($arr['householdcleaning'])) {
            $this->getElement('householdcleaning')->setValue($this->_listing->householdcleaning);
        }

        /*
        if (empty($arr['hongkongyearsexperience'])) {
            $this->getElement('yearexphk')->setValue(!is_numeric($this->_listing->hongkongyearsexperience) ? '': $this->_listing->hongkongyearsexperience);
        }
        if (empty($arr['indonesiayearsexperience'])) {
            $this->getElement('yearexpind')->setValue(!is_numeric($this->_listing->indonesiayearsexperience) ? '': $this->_listing->indonesiayearsexperience);
        }
        if (empty($arr['malaysiayearsexperience'])) {
            $this->getElement('yearexpmal')->setValue(!is_numeric($this->_listing->malaysiayearsexperience) ? '': $this->_listing->malaysiayearsexperience);
        }
        if (empty($arr['middleeastyearsexperience'])) {
            $this->getElement('yearexpmid')->setValue(!is_numeric($this->_listing->middleeastyearsexperience) ? '': $this->_listing->middleeastyearsexperience);
        }
        if (empty($arr['philippinesyearsexperience'])) {
            $this->getElement('yearexpphil')->setValue(!is_numeric($this->_listing->philippinesyearsexperience) ? '': $this->_listing->philippinesyearsexperience);
        }
        if (empty($arr['singaporeyearsexperience'])) {
            $this->getElement('yearexpsing')->setValue(!is_numeric($this->_listing->singaporeyearsexperience) ? '': $this->_listing->singaporeyearsexperience);
        }
        if (empty($arr['taiwanyearsexperience'])) {
            $this->getElement('yearexptai')->setValue(!is_numeric($this->_listing->taiwanyearsexperience) ? '': $this->_listing->taiwanyearsexperience);
        }
        if (empty($arr['thailandyearsexperience'])) {
            $this->getElement('yearexpthai')->setValue(!is_numeric($this->_listing->thailandyearsexperience) ? '': $this->_listing->thailandyearsexperience);
        }        
        if (empty($arr['chinayearsexperience'])) {
            $this->getElement('yearexpchina')->setValue(!is_numeric($this->_listing->chinayearsexperience) ? '': $this->_listing->chinayearsexperience);
        }
        */
        
        if (empty($arr['weight'])) {
            $this->getElement('weight')->setValue($this->_listing->weight);
        }
        if (empty($arr['height'])) {
            $this->getElement('height')->setValue($this->_listing->height);
        }
        if (empty($arr['dateofbirth'])) {
            if (is_object($this->_listing->dateofbirth)) {
                $dob = date('d/m/Y',$this->_listing->dateofbirth->sec);
            } else {
                $dob = $this->_listing->dateofbirth;
            }
            
            $this->getElement('dateofbirth')->setValue($dob);
        }
        /* if (empty($arr['description'])) {
            $this->getElement('description')->setValue($this->_listing->description);
        } */
    }
}